<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="股票名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入股票名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="股票代码" prop="symbol">
        <el-input
          v-model="queryParams.symbol"
          placeholder="请输入股票代码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="TS代码" prop="tsCode">
        <el-input
          v-model="queryParams.tsCode"
          placeholder="请输入TS代码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地域" prop="area">
        <el-input
          v-model="queryParams.area"
          placeholder="请输入地域"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="所属行业" prop="industry">
        <el-input
          v-model="queryParams.industry"
          placeholder="请输入所属行业"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="市场类型" prop="market">
        <el-input
          v-model="queryParams.market"
          placeholder="请输入市场类型"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="板块信息" prop="indexInfo">
        <el-input
          v-model="queryParams.indexInfo"
          placeholder="请输入板块信息"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-card class="base-table" ref="fullTable">
      <TableSetup
        ref="tSetup"
        @onStripe="onStripe"
        @onRefresh="onRefresh"
        @onChange="onChange"
        @onfullTable="onfullTable"
        @onSearchChange="onSearchChange"
        :columns="columns"
        :isTable="isTable"
      >
        <template v-slot:operate>
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['stock:basic:export']"
          >导出</el-button>
        </template>
      </TableSetup>
      <auto-table
        ref="multipleTable"
        class="mytable"
        :tableData="paginatedList"
        :columns="columns"
        :loading="loading"
        :stripe="stripe"
        :tableHeight="tableHeight"
        @onColumnWidthChange="onColumnWidthChange"
        @onSelectionChange="handleSelectionChange"
        @sort-change="handleSortChange"
      >
       
       
        <!--序号-->
        <template #index="{ $index }">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}</span>
        </template>
         <!-- 新增东方财富概念板块信息显示模板 -->
        <template #index_info="{ row }">
          <div v-if="row.index_info && Array.isArray(row.index_info) && row.index_info.length > 0">
            <span 
              v-for="(item, index) in row.index_info" 
              :key="item.index_code"
              class="index-info-link"
              @click="goToDcMember(item.index_code,item.index_name)"
            >
              {{ item.index_name }}
              <span v-if="index < row.index_info.length - 1">, </span>
            </span>
          </div>
          <span v-else></span>
        </template>
        <!--名称可点击-->
        <template #name="{ row }">
          <span class="stock-name-link" @click="handleJumpToBaidu(row)">{{ row.name }}</span>
        </template>
        <template #updateTime="{ row }">
          <span>{{ parseTime(row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
        <template #delistDate="{ row }">
          <span>{{ parseTime(row.delistDate, '{y}-{m}-{d}') }}</span>
        </template>

        <template #listDate="{ row }">
          <span>{{ parseTime(row.listDate, '{y}-{m}-{d}') }}</span>
        </template>

        <template #pctChg="{ row }">
          <span>{{ row.pctChg+'%' }}</span>
        </template>

         <template #operate="{ row }">
          <el-button link type="primary" icon="Position" @click="handleJumpToBaidu(row)">股市通</el-button>
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['stock:basic:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(row)" v-hasPermi="['stock:basic:remove']">删除</el-button> -->
        </template> 
         <!-- 用于显示涨跌幅数据并根据正负值显示不同颜色 -->
         <template #raw_change_3d="{ row }">
          <span :class="getValueColorClass(row.raw_change_3d)">
            {{ formatNumberValue(row.raw_change_3d) }}
          </span>
        </template>

        <template #raw_change_5d="{ row }">
          <span :class="getValueColorClass(row.raw_change_5d)">
            {{ formatNumberValue(row.raw_change_5d) }}
          </span>
        </template>

        <template #raw_change_10d="{ row }">
          <span :class="getValueColorClass(row.raw_change_10d)">
            {{ formatNumberValue(row.raw_change_10d) }}
          </span>
        </template>

        <template #raw_change_20d="{ row }">
          <span :class="getValueColorClass(row.raw_change_20d)">
            {{ formatNumberValue(row.raw_change_20d) }}
          </span>
        </template>

        <template #raw_change_30d="{ row }">
          <span :class="getValueColorClass(row.raw_change_30d)">
            {{ formatNumberValue(row.raw_change_30d) }}
          </span>
        </template>

        <template #raw_change_60d="{ row }">
          <span :class="getValueColorClass(row.raw_change_60d)">
            {{ formatNumberValue(row.raw_change_60d) }}
          </span>
        </template>

        <template #raw_change_90d="{ row }">
          <span :class="getValueColorClass(row.raw_change_90d)">
            {{ formatNumberValue(row.raw_change_90d) }}
          </span>
        </template>

        <template #raw_change_180d="{ row }">
          <span :class="getValueColorClass(row.raw_change_180d)">
            {{ formatNumberValue(row.raw_change_180d) }}
          </span>
        </template>

        <template #raw_change_360d="{ row }">
          <span :class="getValueColorClass(row.raw_change_360d)">
            {{ formatNumberValue(row.raw_change_360d) }}
          </span>
        </template>

        <!-- 前复权数据 -->
        <template #qfq_change_3d="{ row }">
          <span :class="getValueColorClass(row.qfq_change_3d)">
            {{ formatNumberValue(row.qfq_change_3d) }}
          </span>
        </template>

        <template #qfq_change_5d="{ row }">
          <span :class="getValueColorClass(row.qfq_change_5d)">
            {{ formatNumberValue(row.qfq_change_5d) }}
          </span>
        </template>

        <template #qfq_change_10d="{ row }">
          <span :class="getValueColorClass(row.qfq_change_10d)">
            {{ formatNumberValue(row.qfq_change_10d) }}
          </span>
        </template>

        <template #qfq_change_20d="{ row }">
          <span :class="getValueColorClass(row.qfq_change_20d)">
            {{ formatNumberValue(row.qfq_change_20d) }}
          </span>
        </template>

        <template #qfq_change_30d="{ row }">
          <span :class="getValueColorClass(row.qfq_change_30d)">
            {{ formatNumberValue(row.qfq_change_30d) }}
          </span>
        </template>

        <template #qfq_change_60d="{ row }">
          <span :class="getValueColorClass(row.qfq_change_60d)">
            {{ formatNumberValue(row.qfq_change_60d) }}
          </span>
        </template>

        <template #qfq_change_90d="{ row }">
          <span :class="getValueColorClass(row.qfq_change_90d)">
            {{ formatNumberValue(row.qfq_change_90d) }}
          </span>
        </template>

        <template #qfq_change_180d="{ row }">
          <span :class="getValueColorClass(row.qfq_change_180d)">
            {{ formatNumberValue(row.qfq_change_180d) }}
          </span>
        </template>

        <template #qfq_change_360d="{ row }">
          <span :class="getValueColorClass(row.qfq_change_360d)">
            {{ formatNumberValue(row.qfq_change_360d) }}
          </span>
        </template>

        <!-- 后复权数据 -->
        <template #hfq_change_3d="{ row }">
          <span :class="getValueColorClass(row.hfq_change_3d)">
            {{ formatNumberValue(row.hfq_change_3d) }}
          </span>
        </template>

        <template #hfq_change_5d="{ row }">
          <span :class="getValueColorClass(row.hfq_change_5d)">
            {{ formatNumberValue(row.hfq_change_5d) }}
          </span>
        </template>

        <template #hfq_change_10d="{ row }">
          <span :class="getValueColorClass(row.hfq_change_10d)">
            {{ formatNumberValue(row.hfq_change_10d) }}
          </span>
        </template>

        <template #hfq_change_20d="{ row }">
          <span :class="getValueColorClass(row.hfq_change_20d)">
            {{ formatNumberValue(row.hfq_change_20d) }}
          </span>
        </template>

        <template #hfq_change_30d="{ row }">
          <span :class="getValueColorClass(row.hfq_change_30d)">
            {{ formatNumberValue(row.hfq_change_30d) }}
          </span>
        </template>

        <template #hfq_change_60d="{ row }">
          <span :class="getValueColorClass(row.hfq_change_60d)">
            {{ formatNumberValue(row.hfq_change_60d) }}
          </span>
        </template>

        <template #hfq_change_90d="{ row }">
          <span :class="getValueColorClass(row.hfq_change_90d)">
            {{ formatNumberValue(row.hfq_change_90d) }}
          </span>
        </template>

        <template #hfq_change_180d="{ row }">
          <span :class="getValueColorClass(row.hfq_change_180d)">
            {{ formatNumberValue(row.hfq_change_180d) }}
          </span>
        </template>

        <template #hfq_change_360d="{ row }">
          <span :class="getValueColorClass(row.hfq_change_360d)">
            {{ formatNumberValue(row.hfq_change_360d) }}
          </span>
        </template>
      </auto-table>
      <div class="table-pagination">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 添加或修改股票列表对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="basicRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 百度股市通弹出框 -->
    <el-dialog
      title="百度股市通"
      v-model="baiduDialogVisible"
      width="1200px"
      append-to-body
      destroy-on-close
    >
      <iframe 
        :src="baiduStockUrl" 
        width="100%" 
        height="600" 
        frameborder="0"
        style="border-radius: 4px;"
      ></iframe>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="baiduDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 导入数据对话框 -->
    <ImportData
      v-if="openImport"
      v-model="openImport"
      tableName="stock_basic"
      @success="handleImportSuccess"
    />
  </div>
</template>

<script setup name="StockBasic">
import { listBasic, getBasic, delBasic, addBasic, updateBasic, importBasic } from "@/api/stock/basic";
import { listAllTable } from '@/api/system/table'
import TableSetup from '@/components/TableSetup'
import AutoTable from '@/components/AutoTable'
import ImportData from '@/components/ImportData'
const { proxy } = getCurrentInstance();

const basicList = ref([]); // 存储根据所有从后端获取的数据进行过滤排序后的数据
const basicOriginalList = ref([]); // 存储所有从后端获取的原始数据
const paginatedList = ref([]); // 存储当前页需要显示的数据
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const sortField = ref(''); // 当前排序字段
const sortOrder = ref(''); // 当前排序顺序

// 百度股市通弹窗相关
const baiduDialogVisible = ref(false);
const baiduStockUrl = ref('');

const columns = ref([])
const stripe = ref(true)
const isTable = ref(true)
const tableHeight = ref(500)
const fullScreen = ref(false)
const openImport = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    actEntType: null,
    actName: null,
    area: null,
    cnspell: null,
    currType: null,
    delistDate: null,
    enname: null,
    exchange: null,
    fullname: null,
    industry: null,
    isHs: null,
    listDate: null,
    listStatus: null,
    market: null,
    name: null,
    symbol: null,
    tsCode: null,
    indexInfo: null, // 新增板块信息搜索字段
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/**
 * 根据数值正负返回对应的颜色类
 * @param {Number} value - 数值
 * @returns {String} CSS 类名
 */
function getValueColorClass(value) {
  if (value === null || value === undefined) return '';
  if (value > 0) return 'positive-value';
  if (value < 0) return 'negative-value';
  return '';
}

/**
 * 格式化数值显示
 * @param {Number} value - 数值
 * @returns {String} 格式化后的文本
 */
function formatNumberValue(value) {
  if (value === null || value === undefined) return '-';
  return `${value.toFixed(2)}%`;
}
/**
 * 跳转到东方财富板块成分页面
 * @param {string} tsCode - 板块代码
 */
function goToDcMember(tsCode,indexName) {
  // 使用 router.push 跳转到 dc_member 页面，并传递查询参数
  proxy.$router.push({
    path: '/stock/stock_dc_member',
    query: {
      tsCode: tsCode,
      indexName: indexName
    }
  });
}

/** 查询股票列表列表 - 获取所有数据 */
function getList() {
  loading.value = true;
  // 获取所有数据（不传分页参数）
  listBasic({}).then(response => {
    // 处理 otherInfo 数据
    const processedData = response.data.map(item => {
      // 创建新对象避免修改原始数据
      const processedItem = { ...item };
      
      // 解析 otherInfo 字段
      if (item.otherInfo && typeof item.otherInfo === 'string') {
        try {
          const otherInfo = JSON.parse(item.otherInfo);
          if (otherInfo.price_changes) {
            const priceChanges = otherInfo.price_changes;
            
            // 处理每种复权方式
            Object.keys(priceChanges).forEach(type => {
              if (priceChanges[type]) {
                Object.keys(priceChanges[type]).forEach(period => {
                  // 构造字段名，如 raw_change_3d
                  const fieldName = `${type}_${period}`;
                  processedItem[fieldName] = priceChanges[type][period];
                });
              }
            });
          }
        } catch (e) {
          console.error('解析 otherInfo 失败:', e);
        }
      }
      
      return processedItem;
    });
    // basicList.value = processedData;
    basicOriginalList.value = processedData;
    total.value = processedData.length;
    loading.value = false;
    // 应用当前过滤和排序条件
    applyFiltersAndSort();
  });
}

function getColumns() {
  listAllTable({ tableName: 'stock_basic' })
    .then((response) => {
      columns.value = response.data
    })
    .then(() => {
      getList()
    })
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    actEntType: null,        
    actName: null,        
    area: null,        
    cnspell: null,        
    createTime: null,        
    currType: null,        
    delistDate: null,        
    enname: null,        
    exchange: null,        
    fullname: null,        
    id: null,        
    industry: null,        
    isHs: null,        
    listDate: null,        
    listStatus: null,        
    market: null,        
    name: null,        
    symbol: null,        
    tsCode: null,        
    updateTime: null  
  };
  proxy.resetForm("basicRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  applyFiltersAndSort();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加股票列表";
}

/** 新增按钮操作 */
function handleImport() {
  openImport.value = true
}

/** 跳转到百度股市通（弹窗形式） */
function handleJumpToBaidu(row) {
  if (row.symbol) {
    baiduStockUrl.value = `https://gushitong.baidu.com/stock/ab-${row.symbol}?mainTab=%E6%A6%82%E8%A7%88`;
    baiduDialogVisible.value = true;
  } else {
    proxy.$modal.msgWarning("该股票没有股票代码，无法跳转");
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const stockBasicId = row.id || ids.value
  getBasic(stockBasicId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改股票列表";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["basicRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBasic(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBasic(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除股票列表编号为"' + _ids + '"的数据项？').then(function() {
    return delBasic(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('stock/basic/export', {
    ...queryParams.value
  }, `basic_${new Date().getTime()}.xlsx`)
}

//表格全屏
function onfullTable() {
  proxy.$refs.tSetup.onFull(proxy.$refs.fullTable.$el)
  fullScreen.value = !fullScreen.value
  updateTableHeight()
}

//表格刷新
function onRefresh() {
  getList()
}

//搜索框显示隐藏
function onSearchChange() {
  showSearch.value = !showSearch.value
}

function onStripe(val) {
  stripe.value = val
}

//改变表头数据
function onChange(val) {
  columns.value = val
}

//改变表格宽度
function onColumnWidthChange(column) {
  proxy.$refs.tSetup.tableWidth(column)
}

//更新表格高度
function updateTableHeight() {
  if (
    proxy.$refs.tSetup &&
    proxy.$refs.queryRef &&
    document.querySelector('.table-pagination')
  ) {
    if (fullScreen.value) {
      tableHeight.value = window.innerHeight - 145
    } else {
      tableHeight.value =
        window.innerHeight -
        proxy.$refs.tSetup.$el.clientHeight -
        proxy.$refs.queryRef.$el.clientHeight -
        document.querySelector('.table-pagination').clientHeight -
        220
    }
  }
}

//导入成功
function handleImportSuccess(sheetName, filedInfo, fileName) {
  let data = {
    tableName: 'stock_basic',
    filedInfo: filedInfo,
    fileName: fileName,
    sheetName: sheetName
  }
  importBasic(data).then(() => {
    proxy.$modal.msgSuccess('导入成功')
    openImport.value = false
    getList()
  })
  getList()
}

// 处理分页变化
function handlePageChange() {
  updatePaginatedData();
}

// 根据当前页码和每页大小更新显示数据
function updatePaginatedData() {
  const start = (queryParams.value.pageNum - 1) * queryParams.value.pageSize;
  const end = start + queryParams.value.pageSize;
  paginatedList.value = basicList.value.slice(start, end);
}

// 处理排序变化
function handleSortChange({ column, prop, order }) {
  sortField.value = prop;
  sortOrder.value = order;
  applyFiltersAndSort();
}

// 应用过滤和排序条件
function applyFiltersAndSort() {
    let filteredData = [...basicOriginalList.value];
    // 应用搜索过滤
    if (queryParams.value.name) {
      filteredData = filteredData.filter(item => item.name.includes(queryParams.value.name));
    }
    if (queryParams.value.symbol) {
      filteredData = filteredData.filter(item => item.symbol.includes(queryParams.value.symbol));
    }
    if (queryParams.value.tsCode) {
      filteredData = filteredData.filter(item => item.tsCode.includes(queryParams.value.tsCode));
    }
    if (queryParams.value.area) {
      filteredData = filteredData.filter(item => item.area.includes(queryParams.value.area));
    }
    if (queryParams.value.industry) {
      filteredData = filteredData.filter(item => item.industry.includes(queryParams.value.industry));
    }
    if (queryParams.value.market) {
      filteredData = filteredData.filter(item => item.market.includes(queryParams.value.market));
    }
    if (queryParams.value.indexInfo) {
      filteredData = filteredData.filter(item => {
        if (!item.index_info || !Array.isArray(item.index_info)) {
          return false;
        }
        return item.index_info.some(indexItem => 
          indexItem.index_name.includes(queryParams.value.indexInfo)
        );
      });
    }
    // 应用排序
    if (sortField.value && sortOrder.value) {
      const field = sortField.value;
      filteredData.sort((a, b) => {
        let aVal = a[field];
        let bVal = b[field];
        
        // 检查值的类型
        const isAValid = (typeof aVal === 'number' && !isNaN(aVal)) || (typeof aVal === 'string' && aVal !== '');
        const isBValid = (typeof bVal === 'number' && !isNaN(bVal)) || (typeof bVal === 'string' && bVal !== '');
        
        // 如果都不是有效值，认为相等
        if (!isAValid && !isBValid) return 0;
        
        // 如果只有一个是有效值，将有效值排在前面
        if (isAValid && !isBValid) return -1;
        if (!isAValid && isBValid) return 1;
        
        // 都是有效值时进行正常比较
        let result = 0;
        if (typeof aVal === 'number' && typeof bVal === 'number') {
          // 数值比较
          result = aVal - bVal;
        } else {
          // 字符串比较（确保都转换为字符串）
          const strA = String(aVal);
          const strB = String(bVal);
          result = strA > strB ? 1 : (strA < strB ? -1 : 0);
        }
        
        // 根据排序顺序返回结果
        return sortOrder.value === 'ascending' ? result : -result;
      });
    }
    // 更新总数和分页数据
    total.value = filteredData.length;
    basicList.value = filteredData;
    // 调试输出倒数第二页的数据
    // console.log('Total items:', total.value);
    // console.log('Page size:', queryParams.value.pageSize);
    // console.log('Current page:', queryParams.value.pageNum);
    
    // const totalPages = Math.ceil(total.value / queryParams.value.pageSize);
    // if (totalPages >= 2) {
    //   const secondLastPageStart = (totalPages - 2) * queryParams.value.pageSize;
    //   const secondLastPageEnd = Math.min(secondLastPageStart + queryParams.value.pageSize, total.value);
    //   console.log('Second last page data slice:', secondLastPageStart, '-', secondLastPageEnd);
    //   console.log('Second last page data:', filteredData.slice(secondLastPageStart, secondLastPageEnd));
    // }
    updatePaginatedData();
}

onMounted(() => {
  updateTableHeight() // 初始化计算高度
  window.addEventListener('resize', updateTableHeight) // 监听窗口大小变化
})

onUnmounted(() => {
  window.removeEventListener('resize', updateTableHeight) // 销毁监听
})

getColumns()
</script>

<style scoped>
.positive-value {
  color: #f56c6c;
}

.negative-value {
  color: #409eff;
}
.stock-name-link {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}
.stock-name-link:hover {
  color: #66b1ff;
}
.index-info-link {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.index-info-link:hover {
  color: #66b1ff;
}
</style>


